<template>
  <div class="wrap">
    <van-pull-refresh v-model="isLoading" @refresh="onRefresh">



    <div class="topWrap">
      <div class="left" @click="jumpSchoolList">
        <img src="@/assets/addr.png" alt="" />
        <div class="picker">{{ chooseSchoolData.schoolIName }}</div>
      </div>
      <router-link :to="{ name: 'search' }">
        <img src="@/assets/search.png" alt="" class="right" />
      </router-link>
    </div>
    <div class="swiperContaner">
      <van-swipe :autoplay="3000">
        <van-swipe-item
          v-for="(image, index) in bannerData"
          :key="index"
          @click="jumpBanner(image)"
        >
          <img :src="image.bannerImage" />
        </van-swipe-item>
      </van-swipe>
    </div>
    <div class="titleWarp">
      <div
        class="titleItem"
        :class="{ titleItemActiv: chooseId == 0 }"
        @click="reqList(0)"
      >
        推荐
      </div>
      <div
        class="titleItem"
        v-for="(item, index) in resShopTypeList"
        :key="index"
        :class="{ titleItemActiv: chooseId == item.id }"
        @click="reqList(item.id)"
      >
        {{ item.title }}
      </div>
    </div>
    <div class="filterWrap">
      <div class="filterItem" @click="show = true">
        {{ towerInfo.addressName }}
        <img src="@/assets/arrow.png" alt="" class="arrow" />
      </div>
      <div class="filterItem filterItemLine"></div>
      <div class="filterItem" @click="orderBy()">
        销量
        <img src="@/assets/paixu.png" alt="" />
      </div>
    </div>
    <div class="productionList">
      <div v-if="resDayRecInfo.length > 0">
        <div
          class="productionItem"
          @click="jumpShopInfo(item.id)"
          v-for="(item, index) in resDayRecInfo"
          :key="index"
        >
          <div class="proTitle">
            <div class="proLeft">{{ item.shopName }}</div>
            <div class="proRight">{{ item.shopDetailsAddress }}</div>
          </div>
          <div class="proIntroWrap">
            <div class="proIntroLeft">
              <img :src="$imgUrl + item.headImg" alt="" class="proPoster" />
              <img
                src="@/assets/vip.png"
                alt=""
                class="vipImg"
                v-if="item.isDayRec == true || item.recType != 4"
              />
            </div>
            <div class="proIntroRight">
              <div class="proIntro">
                {{ item.intro }}
              </div>
              <div class="salePrice" v-if="item.appCouponList.length > 0">
                <em v-for="(item_, index_) in item.appCouponList" :key="index_"
                  >满{{ item_.thresholdPrice }}减{{
                    item_.discountsPrice
                  }}&nbsp;&nbsp;</em
                >
                <!-- <i
                  v-for="(item_, index_) in item.appCouponList"
                  :key="index_"
                  v-if="index_ % 2 == 0"
                ></i> -->
              </div>
              <div class="salePrice" v-else>暂无优惠</div>
              <div class="workTime">
                <div class="timeLeft">
                  营业：{{ item.startBusinessTime }}-{{ item.endBusinessTime }}
                </div>
                <div class="saleRight">销量:{{ item.totalSaleNum }}</div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="productionItem" v-else>暂无数据...</div>
    </div>
    <div class="pickerMask">
      <van-popup v-model="show">
        <van-picker
          show-toolbar
          title="选择宿舍"
          :columns="columns"
          @confirm="onConfirm"
          @cancel="onCancel"
          @change="onChange"
        >
        </van-picker>
      </van-popup>
    </div>
    <!-- <tabbar></tabbar> -->
    <div style="height: 100px"></div>
    <div class="tabbarWrap">
      <router-link :to="{ name: 'index' }">
        <div class="tabbarItem">
          <img src="@/assets/tabbar1.2.png" alt="" class="tabbarImg" />
          <p class="tabbarText">首页</p>
        </div>
      </router-link>
      <router-link :to="{ name: 'forumIndex' }">
        <div class="tabbarItem">
          <img src="@/assets/tabbar2.1.png" alt="" class="tabbarImg" />
          <p class="tabbarText">论坛</p>
        </div>
      </router-link>
      <router-link :to="{ name: 'personalCenter' }">
        <div class="tabbarItem">
          <img src="@/assets/tabbar3.1.png" alt="" class="tabbarImg" />
          <p class="tabbarText">我的</p>
        </div>
      </router-link>
    </div>
    </van-pull-refresh>

    <div v-if="pulldown" @click="top" class="pulldown"><img class="img_back" src="@/assets/backTop.png" alt=""></div>
  </div>
</template>

<script>
// import Axios from 'axios'
import { Picker, Popup, Swipe, SwipeItem ,Toast ,PullRefresh ,Icon} from "vant";

import {
  apiBanner,
  apiShopTypeList,
  apiUserAddressList,
  apiAddressList,
  apiGetDayRecShopList,
  apiGetShopList,
} from "@/request/api"; // api接口
import tabbar from "../components/tabbar";
export default {
  name: "App",
  data() {
    return {
      show: false,
      columns: ["全部宿舍"],
      imagesBanners: [],
      bannerData: "",
      resShopTypeList: "",
      chooseId: 0, //选择的店铺类型，默认选择的推荐类型id自定义为==0
      chooseSchoolData: "", //选择的校区信息
      resDormList: "", //宿舍楼列表
      reqpageSize: 5, //分页条数
      reqPageNum: 0, //当前第几页
      noMore: false,
      resDayRecInfo: [], //日推店铺列表
      towerInfo: {
        addressName: "宿舍",
        id: "",
      }, //选择的宿舍楼信息
      isAsc: "desc", //排序
      resSchoolList: [], //校区列表

       Top:"",
      WinH:'',
      DocH:"",

      pulldown:false,


       count: 0,
      isLoading: false,
    };
  },
  created() {},
  activated() {
    this.getAddressListSchool();
    this.getUserAddressList();
    this.getBannerReq();
    this.getShopTypeList();
  },
  mounted() {
    var is_loginInfo = JSON.parse(localStorage.getItem("loginInfo"));
    if (!is_loginInfo) {
      //不存在登录信息说明是首次进入，那么需要去获取openid走登录流程
      //获取登录状态和openId：
      this.getOpenId();
    } else {
      //否则不需要再登录直接请求相应接口
      this.getAddressListSchool();
      this.getUserAddressList();
      this.getBannerReq();
      this.getShopTypeList();
      // this.getDayRecInfo();
    }

    // setInterval(()=>{
    //   window.scrollTo(0,500)
    //   console.log();
    // },2000)
  },
  //  跳转后回到指定界面
    beforeRouteEnter(to, from, next) {
      console.log(to);
        next(vm => {
      // 回到原来的位置
      const position = JSON.parse(window.sessionStorage.getItem('position'))
      console.log(position);
      window.scrollTo(0,position)
    })
      

  },
  beforeRouteLeave(to, from, next) {
    console.log(to);
    // 保存离开页面时的位置
    const position = window.scrollY
    window.sessionStorage.setItem('position', JSON.stringify(position))
    next()
  },

  methods: {
     top(){
   window.scrollTo(0,0)
     },
    // 下拉刷新
    onRefresh() {
      setTimeout(() => {
        Toast('刷新成功');
        this.isLoading = false;
        this.count++;
        this.getAddressListSchool();
    this.getUserAddressList();
    this.getBannerReq();
    this.getShopTypeList();
      }, 1000);
    },
    //分页 监听滑动事件
    handleScroll() {
     this.Top = $(window).scrollTop();
      this.WinH = $(window).height();
      this.DocH = $(document).height();

      if(this.Top>1000){
        this.pulldown=true
      }else{
        this.pulldown=false
      }

      // console.log(this.Top,this.WinH,this.DocH);

      if (this.DocH - (this.Top + this.WinH) <= 0) {
        if (this.noMore) {
          return false;
        }
        this.noMore = false;
        if (this.chooseId == 0) {
          this.getDayRecInfo();
        } else {
          this.getShopList();
        }
      }
    },

    //截取code：
    getUrlParam(name) {
      var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
      var r = window.location.search.substr(1).match(reg);
      if (r != null) return unescape(r[2]);
      return null;
    },
    //传code 获取openid
    getOpenId() {
      var code = this.getUrlParam("code"); //截取链接里面的code
      var is_loginInfo = JSON.parse(localStorage.getItem("loginInfo"));
      var that = this;
      $.ajax({
        type: "get",
        async: true,
        url: `${this.$imgUrl}/app/wxAuth/login/${code}`,
        success: function (data) {
          // console.log("首页code获取openid", data.data);
          if (data.code === 200) {
            localStorage.setItem("openId", data.data.openId);
            if (data.data.code === 20015 || !is_loginInfo) {
              //未注册登录跳转登录页面或者登录信息过期了：
              // window.location.href = `${this.$hostName}/#/pages/login`;
              that.$router.replace({
                path: "/pages/login",
              });
            }
            //否则默认停留在首页
          }
        },
      });
    },
    //获取用户地址列表：(查找默认校区)
    getUserAddressList() {
      apiUserAddressList({}).then((res) => {
        var resAddrList = res.data;
        var obj = {
          schoolId: "",
          schoolIName: "",
        };
        if (JSON.parse(sessionStorage.getItem("changeSchoolData"))) {
          //如果选择切换过校区则取上次切换的校区信息
          this.chooseSchoolData = JSON.parse(
            sessionStorage.getItem("changeSchoolData")
          );
          this.getDayRecInfo(); //根据校区请求日推店铺
          this.getAddressList(); //请求宿舍楼列表
          return;
        }

        if (!this.$route.query.chooseSchoolData) {
          //如果没有重新选择校区，那么使用设定的默认地址校区，如果没有默认地址则选择校区列表第一个校区
          if (resAddrList.length == 0) {
            //地址列表为空
            obj.schoolId = this.resSchoolList[0].id;
            obj.schoolIName = this.resSchoolList[0].addressName;
            this.chooseSchoolData = obj;
            sessionStorage.setItem("chooseSchoolData", JSON.stringify(obj));
            sessionStorage.setItem("changeSchoolData", JSON.stringify(obj)); //首页切换的校区

            this.getDayRecInfo(); //根据校区请求日推店铺
            this.getAddressList(); //请求宿舍楼列表
            return;
          }
          //地址列表不为空
          resAddrList.map((item) => {
            if (item.status == 1) {
              //地址列表有地址且有默认地址
              obj.schoolId = item.addressId;
              obj.schoolIName = item.schoolName;
            }
          });
          if (obj.schoolId == "") {
            //地址列表有地址没有默认地址
            obj.schoolId = resAddrList[0].addressId;
            obj.schoolIName = resAddrList[0].schoolName;
          }
          this.chooseSchoolData = obj;
          sessionStorage.setItem(
            "chooseSchoolData",
            JSON.stringify(this.chooseSchoolData)
          );
          sessionStorage.setItem(
            "changeSchoolData",
            JSON.stringify(this.chooseSchoolData)
          ); //首页切换的校区

          this.getDayRecInfo(); //根据校区请求日推店铺
          this.getAddressList(); //请求宿舍楼列表
        } else {
          //如果重新选择了地址
          // this.chooseSchoolData = JSON.parse(sessionStorage.getItem('chooseSchoolData'))
          this.chooseSchoolData = this.$route.query.chooseSchoolData;
          sessionStorage.setItem(
            "chooseSchoolData",
            JSON.stringify(this.$route.query.chooseSchoolData)
          );
          sessionStorage.setItem(
            "changeSchoolData",
            JSON.stringify(this.$route.query.chooseSchoolData)
          ); //首页切换的校区
        }
        console.log("当前展示的校区信息", this.chooseSchoolData);
        this.getDayRecInfo(); //根据校区请求日推店铺
        this.getAddressList(); //请求宿舍楼列表
      });
    },

    //获取某校区宿舍楼列表：
    getAddressList() {
      apiAddressList({
        id: this.chooseSchoolData.schoolId,
      }).then((res) => {
        this.resDormList = res.data;
        this.resDormList.map((item) => {
          this.columns.push(item.addressName);
        });
        // console.log("宿舍楼", this.resDormList);
        // console.log("columns", this.columns);
      });
    },
    //获取校区列表：
    getAddressListSchool() {
      apiAddressList({
        id: -1,
      }).then((res) => {
        this.resSchoolList = res.data;
        // console.log("校区列表", this.resSchoolList);
      });
    },
    //获取banner：
    getBannerReq() {
      apiBanner({}).then((res) => {
        this.bannerData = res.data;
        this.bannerData.map((item) => {
          item.bannerImage = `${this.$imgUrl}${item.bannerImage}`;
          // this.imagesBanners.push(`${this.$imgUrl}${item.bannerImage}`);
        });
        console.log("res-banner", res);
      });
    },

    //获取首页店铺类型：
    getShopTypeList() {
      apiShopTypeList({}).then((res) => {
        this.resShopTypeList = res.data;
        console.log("店铺类型:", this.resShopTypeList);
        // 获取数据成功后的其他操作
      });
    },

    //点击店铺类型：
    reqList(id) {
      this.chooseId = id;
      this.noMore = false;
      this.reqPageNum = 0;
      this.resDayRecInfo = [];
      if (this.chooseId == 0) {
        this.getDayRecInfo();
      } else {
        this.getShopList();
      }
    },

    //获取首页日推店铺-推荐：
    getDayRecInfo() {
      var page = (this.reqPageNum += 1);
      console.log("page", page);
      apiGetDayRecShopList({
        pageNum: page,
        pageSize: this.reqpageSize,
        schoolId: this.chooseSchoolData.schoolId,
        towerId: this.towerInfo.id,
        orderByColumn: "totalSaleNum",
        isAsc: this.isAsc,
      }).then((res) => {
        if (res.data.rows.length == 0) {
          this.noMore = true;
          return;
        }
        var dataRes = res.data.rows;
        this.resDayRecInfo = [...this.resDayRecInfo, ...dataRes];
        console.log("resDayRecInfo-推荐", this.resDayRecInfo);
      });
      window.addEventListener("scroll", this.handleScroll, true);
    },

    //获取店铺列表-分类:
    getShopList() {
      var page = (this.reqPageNum += 1);
      apiGetShopList({
        pageNum: page,
        pageSize: this.reqpageSize,
        shopTypeId: this.chooseId,
        schoolId: this.chooseSchoolData.schoolId,
        towerId: this.towerInfo.id,
        isAsc: this.isAsc,
      }).then((res) => {
        if (res.data.rows.length == 0) {
          this.noMore = true;
          return;
        }
        var dataRes = res.data.rows;
        this.resDayRecInfo = [...this.resDayRecInfo, ...dataRes];
        console.log("resDayRecInfo-类型", this.resDayRecInfo);
      });
    },
    //切换销量：
    orderBy() {
      this.isAsc = this.isAsc == "desc" ? "asc" : "desc";
      this.noMore = false;
      this.reqPageNum = 0;
      this.resDayRecInfo = [];
      if (this.chooseId == 0) {
        this.getDayRecInfo();
      } else {
        this.getShopList();
      }
    },
    //切换宿舍：
    onConfirm(value, index) {
      // console.log('选择的宿舍',value,index)
      this.show = false;
      var index_ = index - 1;
      this.towerInfo.addressName =
        index_ < 0 ? "宿舍" : this.resDormList[index_].addressName;
      this.towerInfo.id = index_ < 0 ? "" : this.resDormList[index_].id;
      this.noMore = false;
      this.reqPageNum = 0;
      this.resDayRecInfo = [];
      if (this.chooseId == 0) {
        this.getDayRecInfo();
      } else {
        this.getShopList();
      }
    },
    onChange(picker, value, index) {},
    onCancel() {
      this.show = false;
    },
    //选择校区：
    jumpSchoolList() {
      console.log("选择校区2222");
      this.$router.replace({
        path: "/pages/schoolList",
        query: { fromId: 2 },
      });
    },
    jumpBanner(dataItem) {
      if (dataItem.type == 0) {
        //无须跳转
      } else if (dataItem.type == 1) {
        //跳转店铺
        this.$router.push({
          path: "/pages/shopInfo",
          query: {
            //传递参数
            shopId: dataItem.shopId,
          },
        });
      } else if (dataItem.type == 2) {
        //跳转外部链接
        window.location.href = dataItem.toPageUrl;
      }
    },

    jumpShopInfo(id) {
      this.$router.push({
        path: "/pages/shopInfo",
        query: {
          //传递参数
          shopId: id,
        },
      });
    },
  },
  created() {},
  deactivated() {
    window.removeEventListener("scroll", this.handleScroll, true);
  },
  components: {
    tabbar,
    [Picker.name]: Picker,
    [Popup.name]: Popup,
    [Swipe.name]: Swipe,
    [SwipeItem.name]: SwipeItem,
    [PullRefresh.name]: PullRefresh,
    [Icon.name]: Icon,

  },
};
</script>

<style scoped>
.van-swipe-item img {
  width: 100%;
}
.wrap {
  background-color: #f2f3f9;
  padding: 0px 15px;
  padding-top: 20px;
}
.topWrap {
  width: 100%;
  display: flex;
  justify-content: space-between;
}
.topWrap .left {
  padding: 14px 18px;
  background: #ffffff;
  border-radius: 20px;
  font-size: 13px;
  font-weight: 500;
  color: #181818;
}
.topWrap .left img {
  width: 17px;
  height: 18px;
  padding-right: 10px;
}
.picker {
  float: right;
}
.topWrap .right {
  display: block;
  width: 17px;
  height: 17px;
  margin-top: 16px;
  margin-right: 4rpx;
}
.pickerMask {
}
.van-picker {
  width: 100vw;
}
.van-popup--center {
  top: 77%;
}
.swiperContaner .van-swipe {
  margin-top: 15px;
  margin-bottom: 20px;
  width: 100%;
  height: 160px;
  background: #181818;
  box-shadow: 0px 6px 8px 0px rgba(148, 148, 148, 0.16);
  border-radius: 20px;
  /* .van-swipe */
}
.swiperContaner > img {
  width: 100%;
  height: auto;
}
.van-swipe-item {
  height: 150px;
}
.titleWarp {
  width: calc(100% - 30px);
  margin: 20px auto;
  height: 35px;
  line-height: 30px;
  overflow-y: hidden;
  overflow-x: scroll;
  display: -webkit-box;
}
.titleItem {
  font-size: 15px;
  font-weight: 500;
  color: #181818;
  margin-right: 30px;
  /* overflow: hidden; */
  /* float: left; */
}
.titleItemActiv {
  font-size: 21px;
  font-weight: 500;
  color: #181818;
  border-bottom: 4px solid #000;
}
.filterWrap {
  width: calc(100% - 26px);
  height: 34px;
  line-height: 34px;
  background: #181818;
  border-radius: 17px;
  font-size: 12px;
  font-weight: 500;
  color: #666666;
  padding-left: 26px;
  margin-top: 10px;
}
.filterItem {
  float: left;
  margin-right: 15px;
}
.filterItem > img {
  width: 5px;
  height: 5px;
  padding-bottom: 3px;
}
.filterItem .arrow {
  width: 5px;
  height: 3px;
}
.filterItemLine {
  height: 15px;
  width: 1px;
  background-color: #666666;
  margin-top: 10px;
}
.productionList {
}
.productionItem {
  width: calc(100% - 30px);
  min-height: 130px;
  background: #ffffff;
  border-radius: 20px;
  padding: 15px;
  margin-top: 15px;
}
.proTitle {
  width: 100%;
  display: flex;
  justify-content: space-between;
}
.proLeft {
  font-size: 15px;
  font-weight: 500;
  color: #181818;
  width: 65%;
  height: 20px;
  line-height: 20px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
.proRight {
  font-size: 10px;
  font-weight: 300;
  color: #666666;
}
.proIntroWrap {
  width: 100%;
  display: flex;
  justify-content: space-between;
  margin-top: 10px;
}
.proIntroLeft {
}
.proPoster {
  width: 25%;
  height: 75px;
  position: absolute;
  border-radius: 12px;
}
.vipImg {
  width: 30px;
  height: 15px;
  position: absolute;
  left: 94px;
}
.proIntroRight {
  width: 65%;
}
.proIntro {
  font-size: 10px;
  font-weight: 400;
  color: #181818;
  text-overflow: -o-ellipsis-lastline;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
}
.salePrice {
  font-size: 9px;
  font-weight: 400;
  color: #ff5252;
  /* padding: 3px 8px; */
  border: 1px solid #ff5252;
  border-radius: 7px;
  /* width: 100px; */
  margin: 10px 0px 5px 0px;
  text-align: center;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}
em {
  font-style: normal;
}
i {
  display: inline-block;
  width: 1px;
  height: 10px;
  background-color: #ff5252;
  margin: 0px 2px;
}
.workTime {
  width: 100%;
  display: flex;
  justify-content: space-between;
  font-size: 10px;
  font-weight: 400;
  color: #999999;
}
.timeLeft {
}
.saleRight {
}

.pulldown{
  position: fixed;
  bottom: 110px;
  right: 30px;

  border-radius: 50%;

}
.img_back{
  width: 40rpx;
  height: 40px;
}
</style>
